package com.happy016.controller;


import com.happy016.entity.user.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;


/**
 *
 * @author Linyb
 * create on 2017/8/4 10:27
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/to")
    public String to(){
        return "insertUser";
    }

    //效验user
    //user里面创建时间 如果前端传过来 2017-06-06 会报类型转换异常
    // Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'createTime';
    // nested exception is org.springframework.core.convert.ConversionFailedException:
    // Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2017-06-06';
    // nested exception is java.lang.IllegalArgumentException
    // 解决方案:自定义Binding规则
    //
    @RequestMapping(value = "/insert",method = RequestMethod.POST)
    @ResponseBody
    public String insertUser(@Valid User user, BindingResult result){
        if (result.hasErrors()){

            //获取所有得error
            //List<FieldError> allError = result.getFieldErrors();
            //List<ObjectError> allErrorObj = result.getAllErrors();
            //result.getErrorCount();
            //result.getFieldErrorCount();
            //......

            //获取第一个error
            FieldError error = result.getFieldError();
            return error.getDefaultMessage(); //返回default error信息,在实体类里面配
        }
        return "success";
    }
}
